<template>
  <div :class="prefixCls">
    <quill-editor
      v-model="content"
      :ref="myQuillEditor"
      :options="editorOption"
      @blur="onEditorBlur($event)"
      @focus="onEditorFocus($event)"
      @ready="onEditorReady($event)"
      @change="onEditorChange($event)"
    ></quill-editor>
  </div>
</template>

<script>
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import Quill from "quill";

import { quillEditor } from "vue-quill-editor";

import ImageResize from "quill-image-resize-module";

Quill.register("modules/imageResize", ImageResize);

console.log(Quill);
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image"],
  ["clean"], // remove formatting button
];
export default {
  name: "QuillEditor",
  components: {
    quillEditor,
  },
  props: {
    prefixCls: {
      type: String,
      default: "ant-editor-quill",
    },
    // 表单校验用字段
    // eslint-disable-next-line
    value: {
      type: String,
    },
    myQuillEditor: {
      type: String,
    },
  },
  data() {
    /*富文本编辑图片上传配置*/
    const uploadConfig = {
      action: "admin/sys-file/upload", // 必填参数 图片上传地址
      methods: "POST", // 必填参数 图片上传方式
      token: this.$store.getters.access_token, // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
      name: "file", // 必填参数 文件的参数名
      size: 5242880, // 可选参数   图片大小，单位为Kb, 1M = 1024Kb
      accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon", // 可选 可上传的图片格式
      Authorization: "Bearer " + this.$store.getters.access_token,
    };
    const handlers = {
      image: function image() {
        var self = this;

        var fileInput = this.container.querySelector(
          "input.ql-image[type=file]"
        );
        if (fileInput === null) {
          fileInput = document.createElement("input");
          fileInput.setAttribute("type", "file");
          // 设置图片参数名
          if (uploadConfig.name) {
            fileInput.setAttribute("name", uploadConfig.name);
          }
          // 可设置上传图片的格式
          fileInput.setAttribute("accept", uploadConfig.accept);
          fileInput.classList.add("ql-image");
          // 监听选择文件
          fileInput.addEventListener("change", function () {
            // 创建formData
            var formData = new FormData();
            formData.append(uploadConfig.name, fileInput.files[0]);
            // 图片上传
            var xhr = new XMLHttpRequest();
            xhr.open(uploadConfig.methods, uploadConfig.action, true);

            if (uploadConfig.token) {
              xhr.setRequestHeader("token", uploadConfig.token); // 可以定义请求头带给后端
              xhr.setRequestHeader("Authorization", uploadConfig.Authorization);
            }
            // 上传数据成功，会触发
            xhr.onload = function (e) {
              if (xhr.status === 200) {
                var res = JSON.parse(xhr.responseText);
                let length = self.quill.getSelection(true).index;
                //这里很重要，你图片上传成功后，img的src需要在这里添加，res.path就是你服务器返回的图片链接。
                console.log(res);
                self.quill.insertEmbed(length, "image", res.data.url);
                self.quill.setSelection(length + 1);
              }
              fileInput.value = "";
            };
            // 开始上传数据
            xhr.upload.onloadstart = function (e) {
              fileInput.value = "";
            };
            // 当发生网络异常的时候会触发，如果上传数据的过程还未结束
            xhr.upload.onerror = function (e) {};
            // 上传数据完成（成功或者失败）时会触发
            xhr.upload.onloadend = function (e) {
              // console.log('上传结束')
            };
            xhr.send(formData);
          });
          this.container.appendChild(fileInput);
        }
        fileInput.click();
      },
    };
    return {
      content: null,
      editorOption: {
        // some quill options
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: handlers,
          },
          imageResize: {
            // 图片缩放比例
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white",
            },
            modules: ["Resize", "DisplaySize", "Toolbar"], // Resize 允许缩放， DisplaySize 缩放时显示像素 Toolbar 显示工具栏
          },
        },
      },
    };
  },
  methods: {
    onEditorBlur(quill) {
      console.log("editor blur!", quill);
    },
    onEditorFocus(quill) {
      // console.log('editor focus!', quill)
    },
    onEditorReady(quill) {
      console.log("editor ready!", quill);
      this.content = this.value;
    },
    onEditorChange({ quill, html, text }) {
      // console.log('editor change!', quill, html, text)
      this.$emit("editorChange", quill, html, text);
    },
  },
  watch: {
    value(val) {
      this.content = val;
    },
  },
};
</script>

<style lang="scss">
.ql-editor {
  height: 800px;
}
.ql-formats {
  line-height: normal;
}
</style>
